package service

import (
	"errors"
	"fmt"
	"kong-social-api/modules/login/model/context"
	"kong-social-api/modules/login/model/dto"
	"kong-social-api/modules/login/model/vo"
	"kong-social-api/modules/user/mapper"
	"kong-social-api/utils"
	"kong-social-api/utils/rdb"
)

type LoginService struct{}

var userMapper = mapper.UserMapper{}

// 根据手机号码查询用户信息
func (service *LoginService) LoginByPhoneAndPassword(ctx *context.LoginContext) (o *vo.LoginVo, err error) {
	// 根据手机号、账号、用户名查询
	user := userMapper.GetUserByTelephone(ctx.Telephone)
	if user == nil {
		user = userMapper.GetUserByAccount(ctx.Telephone)
		if user == nil {
			user = userMapper.GetUserByUserName(ctx.Telephone)
			if user == nil {
				return nil, errors.New("找不到用户信息！！！")
			}
		}
	}

	// 根据输入的密码进行校验
	md5Password := utils.Md5Slat(ctx.Password, user.Slat)
	if user.Password != md5Password {
		return nil, errors.New("输入的密码有误！")
	}
	// 开始把登录的用户信息，生成token进行返回
	loginVo := vo.LoginVo{}
	loginVo.Uuid = utils.GetUUID()
	loginVo.UserName = user.UserName
	loginVo.UserAvatar = user.Avatar
	loginVo.UserPhone = user.Telephone
	loginVo.UserAddress = user.Address
	loginVo.UserNickname = user.NickName
	// 把登录的用户信息写入到缓存中 --map
	cacheKey := fmt.Sprintf("LOGIN:USER:%s", loginVo.Uuid)
	// 这里把用用户需要的信息，放入缓存中
	userDto := dto.UserDto{}
	utils.CopyProperties(&userDto, user)
	// 开始把用户信息写入到缓存中
	rdb.RdbHSet(cacheKey, "user", utils.StructToJson(userDto))
	return &loginVo, nil
}
